package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImp implements UserService {
    private User user = new User();
    @Autowired
    WeChatProperties weChatProperties;
    
    @Autowired
    UserMapper userMapper;
    private final String wx_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public UserLoginVO wechatlogin(UserLoginDTO userLoginDTO) {

        //调用微信接口服务（官方提供）,得到openid
        Map<String,Object> map = new HashMap<>();
        //申请微信小程序给的
        map.put("appid",weChatProperties.getAppid());
        //申请微信小程序给的
        map.put("secret",weChatProperties.getSecret());
        //微信小程序返回的
        map.put("js_code",userLoginDTO.getCode());
        //固定参数
        map.put("grant_type","authorization_code");

        String json = HttpClientUtil.doGet(wx_LOGIN, map);
        //把字符串变成JSON对象
        JSONObject jsonObject = JSON.parseObject(json);
        Object openid = jsonObject.get("openid");
        //判断openid是否为空，空表示登录失败
        if (openid==null)
        {
            throw new BaseException("登录失败");
        }
        //查询用户
        user =  userMapper.selectuser(openid);

        //判断是否是新用户，是就创建
        if (user==null)
        {
            user = new User();
            user.setOpenid((String) openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

       User user1 = userMapper.selectuser(openid);
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user1,userLoginVO);
        return userLoginVO;
    }
}
